﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Collections.ObjectModel;
using System.Linq.Expressions;
using XYAC.Framework.WohuaMesExtend.IHI.Extensions;
using XYAC.Framework.WohuaMesExtend.IHI.LocalData.Models;
using XYAC.Framework.WohuaMesExtend.IHI.Services;

namespace XYAC.Framework.WohuaMesExtend.IHI.ViewModels
{
    public partial class QualityDataHistoryViewModel : ViewModelBase
    {
        public QualityDataHistoryViewModel(IOptionsMonitor<AppConfig> options, ILogger<QualityDataHistoryViewModel> logger, IServiceProvider serviceProvider)
        {

            this.CurrentAppConfig = options;
            this.Logger = logger;
            this.Provider = serviceProvider;
            this.ChkAutoStartIsChecked = AutoStartupHelper.IsAutoStartupEnabled();
            //LoadCurrentSelectionSpecInfo();
        }

        public IOptionsMonitor<AppConfig> CurrentAppConfig { get; }
        public ILogger<QualityDataHistoryViewModel> Logger { get; }
        public IServiceProvider Provider { get; }

        [ObservableProperty]
        private IEnumerable<string> _querySpecComboSource;
        /// <summary>
        /// 本地数据总量
        /// </summary>
        [ObservableProperty]
        private int _totalLocalDataPageCount;
        [ObservableProperty]
        private int _totalLocalDataPageIndex = 1;

        /// <summary>
        /// 表格数据源
        /// </summary>
        [ObservableProperty]
        private IEnumerable<LocalRecord> _recordsDataGridSource;

        /// <summary>
        /// 条件查询
        /// </summary>
        [ObservableProperty]
        public string _userChoiceQuerySpec;
        /// <summary>
        /// 是否为条件查询
        /// </summary>
        [ObservableProperty]
        public bool _chkAutoStartIsChecked;
        /// <summary>
        /// 查询结束时间
        /// </summary>
        [ObservableProperty]
        public DateTimeOffset? _endDatePickerSelectedDate = DateTimeOffset.Now.AddDays(1);
        /// <summary>
        /// 查询开始时间
        /// </summary>
        [ObservableProperty]
        public DateTimeOffset? _startDatePickerSelectedDate = DateTimeOffset.Now.AddDays(-1);



        /// <summary>
        /// 通过条件刷新数据
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        private void RefershLocalRecordsViaConditions(int pageIndex = -1, int pageSize = 20)
        {
            try
            {

                using (var scope = this.Provider.CreateScope())
                {
                    try
                    {
                        var localDbService = scope.ServiceProvider.GetService<LocalDataService>();
                        var startDate = this.StartDatePickerSelectedDate;
                        var endDate = this.EndDatePickerSelectedDate;
                        List<Expression<Func<LocalRecord, bool>>> filterCondition = new List<Expression<Func<LocalRecord, bool>>>();

                        if (startDate.HasValue)
                        {
                            filterCondition.Add(T => T.LastSyncDate >= startDate.Value.DateTime);
                        }
                        if (endDate.HasValue)
                        {
                            filterCondition.Add(T => T.LastSyncDate < endDate.Value.DateTime.AddDays(1));
                        }
                        if (!string.IsNullOrEmpty(this.UserChoiceQuerySpec?.ToString()))
                        {

                            filterCondition.Add(T => T.SpecInfo == this.UserChoiceQuerySpec.ToString());
                        }
                        var orderConditionDesc = new List<Expression<Func<LocalRecord, object>>>();
                        orderConditionDesc.Add(T => T.LastSyncDate);

                        var pageCount = localDbService.GetCount<LocalRecord>() / pageSize;

                        this.TotalLocalDataPageCount = pageCount;

                        var LocalRecords = localDbService.GetPage<LocalRecord>(pageIndex - 1, pageSize, filterCondition, orderConditionDescs: orderConditionDesc);


                        try
                        {
                            this.RecordsDataGridSource = new ObservableCollection<LocalRecord>(LocalRecords);

                        }
                        catch (Exception ex)
                        {
                            Logger?.LogError($"刷新本地生产记录出现异常:{ex.Message}{ex.StackTrace}", ex);

                        }
                    }
                    catch (Exception ex)
                    {
                        Logger?.LogError($"查询本地生产记录失败:{ex.Message}{ex.StackTrace}", ex);
                        //GlobalParams.ShowMessageBox(
                        //                       new ButtonEnumLocal[] { ButtonEnumLocal.OK },
                        //                       ContentMessage: "查询本地生产记录失败:" + ex.Message,
                        //                       msgHeader: "查询失败",
                        //                       icon: Icon.Warning);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger?.LogError(ex.Message, ex);
            }
        }

        /// <summary>
        /// 刷新数据
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        private void RefershLocalRecords(int pageIndex = -1, int pageSize = 20)
        {
            Task.Run(() =>
            {
                try
                {
                    using (var scope = this.Provider.CreateScope())
                    {

                        var localDbService = scope.ServiceProvider.GetService<LocalDataService>();
                        var pageCount = Convert.ToInt32(Math.Ceiling(localDbService.GetCount<LocalRecord>() * 1D / pageSize));
                        //To Do
                        this.TotalLocalDataPageCount = pageCount;


                        var orderConditionDesc = new List<Expression<Func<LocalRecord, object>>>();
                        orderConditionDesc.Add(T => T.LastSyncDate);

                        var LocalRecords = localDbService.GetPage<LocalRecord>(pageIndex - 1, pageSize, orderConditionDescs: orderConditionDesc);
                        try
                        {
                            this.RecordsDataGridSource = new ObservableCollection<LocalRecord>(LocalRecords);

                        }
                        catch (Exception ex)
                        {
                            Logger?.LogError($"刷新同步记录出现异常:{ex.Message}{ex.StackTrace}", ex);


                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger?.LogError($"查询本地生产记录失败:{ex.Message}{ex.StackTrace}", ex);

                }
            });

        }




        [RelayCommand]
        public void QueryLocalDataHistory()
        {
            try
            {
                if (this.ChkAutoStartIsChecked == true)
                {
                    RefershLocalRecordsViaConditions(this.TotalLocalDataPageIndex, 20);
                }
                else
                {
                    RefershLocalRecords(this.TotalLocalDataPageIndex, 20);
                }
            }
            catch (Exception ex)
            {

                Logger?.LogError(ex.Message, ex);
            }

        }


        /// <summary>
        /// 下一页
        /// </summary>
        [RelayCommand]
        public void LocalDataNextPage()
        {
            try
            {
                if (this.TotalLocalDataPageIndex + 1 > TotalLocalDataPageCount)
                {
                    this.TotalLocalDataPageIndex = TotalLocalDataPageCount;
                }
                else
                {
                    this.TotalLocalDataPageIndex++;
                }

                RefershLocalRecords(this.TotalLocalDataPageIndex);
            }
            catch (Exception ex)
            {

                Logger?.LogError(ex.Message, ex);
            }
        }
        /// <summary>
        /// 上一页
        /// </summary>
        [RelayCommand]
        public void LocalDataForwardPage()
        {

            try
            {
                if (this.TotalLocalDataPageIndex - 1 <= 0)
                {
                    this.TotalLocalDataPageIndex = 1;
                }
                else
                {
                    this.TotalLocalDataPageIndex--;
                }

                RefershLocalRecords(this.TotalLocalDataPageIndex);
            }
            catch (Exception ex)
            {

                Logger?.LogError(ex.Message, ex);
            }
        }


    }
}
